package base.core.config;

import base.core.util.Dates;
import base.core.util.Jacksons;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig {

    /**
     * 全局的ObjectMapper  主要是设置日期序列化规则
     * @return
     */
    @Bean
    public ObjectMapper objectMapper(){
        return Jacksons.getObjectMapper();
    }

    /**
     * 参数反序列化规则-LocalDateTime
     */
    @Bean
    public Converter<String, LocalDateTime> addDateTimeConverter() {
        return new Converter<String, LocalDateTime>(){
            @Override
            public LocalDateTime convert(String source) {
                LocalDateTime localDateTime = Dates.asLocalDateTime(source);
                return localDateTime;
            }
        };
    }

    /**
     * 参数反序列化规则-LocalDate
     */
    @Bean
    public Converter<String, LocalDate> addDateConvert() {
        return new Converter<String, LocalDate>(){
            @Override
            public LocalDate convert(String source) {
                LocalDate localDate = Dates.asLocalDate(source);
                return localDate;
            }
        };
    }

    /**
     * @return MappingJackson2HttpMessageConverter
     * @Description 响应过滤
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter(ObjectMapper objectMapper) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = objectMapper;
        converter.setObjectMapper(mapper);
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypes);
        return converter;
    }
}
